package com.smm.web.vmc.handler;

import com.smm.web.vmc.domain.Receipt;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;

public class MinaClient {


    /**
     * 点亮仓单
     * @param rep
     */
    public static void litReceipt(Receipt rep){

        IoConnector connector = new NioSocketConnector();

        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyEncoder("UTF-8"), new MyDecoder("UTF-8")));

        connector.setHandler(new IoHandlerAdapter(){


            @Override
            public void sessionOpened(IoSession session) throws Exception {

                System.out.println("open session");

            }



            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                System.out.println("从服务器接收消息： [" + message.toString() + "]");

                //发送信息，检查服务器状态
                session.write("type:server");

                //如果服务器正常
                if(message.equals("211 system:connected (type=server)")){

                    //发送点亮指令
                    if(StringUtils.isNotBlank(rep.getLedOrder())){

                        session.write("hit:"+rep.getLedOrder().trim());

                    }else{

                        session.closeNow();

                        session.getService().dispose();
                    }


                }

                //如果服务器返回点亮成功， 关闭session
                if(message.equals("301 hit:sent")){

                    session.closeNow();

                    session.getService().dispose();
                }

            }


        });

        connector.connect(new InetSocketAddress("172.16.9.111", 3333));


    }




    public static void main(String[] args) {

//        MinaClient.litReceipt("1");

    }
}
